import Env from '@/env'
import CryptoJS from 'crypto-js'
import Tool from '@/libs/tool'
import { useMpUser } from '@/stores/mpUser'

let _initMpUser = {
    id: 0,
    avatar: '',
    gender: 0,
    token: 0,
    key: 0,
    nickname: '',
    mobile: ''
}

const Api = {
    getUrl() {
        return Env.apiUrl;
    },
    getServerApiBaseUri() {
        return this.getUrl() + Env.appUri;
    },
    getUri(uri) {
        return this.getServerApiBaseUri() + uri;
    },
    img(w = 300, h = null) {
        let queryObj = {w: w, h: h || w}
        return this.getServerApiBaseUri() + '/guest/pub/gd?' + Tool.objectToQueryString(queryObj);
    },
    generateFormParams: function (params = {}) {
        // let _this = this;
        let _timestamp = Tool.getTimestamp();
        let _nonce = _timestamp + "_nonce_" + Math.random() + Math.random() + Math.random() + Math.random();
        params.token = useMpUser().getMpUser.token;
        params.key = useMpUser().getMpUser.key;
        params.nonce = _nonce;
        params.timestamp = _timestamp;
        delete params["sign"];
        let keys = Object.keys(params);
        keys.sort();
        let arr = [];
        for(let index in keys){
            arr[index] = keys[index] + "=" + params[keys[index]];
        }
        let _sign = arr.join("&");
        _sign = CryptoJS.MD5(_sign).toString();
        params.sign = _sign;
        delete params.token;
        delete params.key;
        return params;
    },
    guestPost(uri, data) {
        let _this = this;
        return _this.post(uri, data, false)
    },
    post(uri, data, isAuth = true, withLoading = true) {
        let _this = this;
        if (withLoading) {
            uni.showLoading({
                title: '请求中',
                mask: true
            });
        }
        let headers = {
            'Content-Type': 'application/x-www-form-urlencoded'
        }
        if (isAuth) {
            headers.Authorization = "Bearer " + useMpUser().getMpUser.token;
            data = _this.generateFormParams(data);
        }
        return new Promise((resolve, reject) => {
            uni.request({
                url: _this.getUri(uri),
                method: 'POST',
                data: data,
                header: headers,
                success: (res) => {
                    if (withLoading) {
                        uni.hideLoading();
                    }
                    // 处理请求成功的情况
                    if (res.statusCode === 200 && res.data.code === 200) {
                        resolve(res.data);
                    } else {
                        // 如果服务器返回的不是200，可以在这里处理错误
                        useMpUser().updateMpUser(_initMpUser);
                        let title = res.message || res.data.message || res.data;
                        uni.showToast({
                            title: title,
                            icon: "none"
                        })
                        _this.mpLogin()
                        reject(res);
                    }
                },
                fail: (err) => {
                    if (withLoading) {
                        uni.hideLoading();
                    }
                    // 处理请求失败的情况
                    uni.showToast({
                        title: err.message || err.data.message,
                        icon: "none"
                    })
                    reject(err);
                }
            });
        });
    },
    mpLogin() {
        let _this = this;
        return new Promise((resolve, reject) => {
            if (!useMpUser().getMpUser.token) {
                console.log("setMpUser")
                uni.getUserInfo({
                    success(res1) {
                        uni.login({
                            success(res2) {
                                // console.log(res1, res2)
                                let postData = {
                                    mp_code: res2.code,
                                    mp_appid: Env.appid,
                                    user_info: JSON.stringify(res1)
                                }
                                _this.guestPost('/site/mp-login', postData).then(res3 => {
                                    useMpUser().updateMpUser(res3.data.mpUser)
                                    resolve()
                                })
                            },
                            fail(err) {
                                reject(err)
                            }
                        })
                    },
                    fail(err) {
                        reject(err)
                    }
                })
            } else {
                console.log("hasMpUser")
                resolve()
            }
        })
    }
}

export default Api
